/**
 * $Id: NoticeUtils.java Dec 8, 2014 5:25:44 PM hdp
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.gzjp.common.utils.pay;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;



public final class NoticeUtils {
	/**
	 * 日志
	 */
	private static final Logger LOG = LoggerFactory.getLogger(NoticeUtils.class);
	private NoticeUtils() {
		throw new RuntimeException("不能初始化");
	}
	/**
	 * 通知地址
	 */
	public static final String NOTICE_URL;
	/**
	 * 失败重试次数
	 */
	public static final int RETRY_TIMES;
	
	static {
		// TODO：可以读取properties文件
		Properties props = new Properties();
		InputStream inputStream = NoticeUtils.class.getClassLoader().getResourceAsStream("notice.cfg.properties");
		try {
			props.load(inputStream);
			NOTICE_URL = props.getProperty("NOTICE_URL");
			String tryTime = props.getProperty("RETRY_TIMES");
			RETRY_TIMES = Integer.parseInt(tryTime);
		} catch (Exception e) {
			throw new ExceptionInInitializerError("notice.cfg.properties文件加载失败");
		}
		
	}
	
	/**
	 * 支付成功后异步通知app后台,采用post,如果失败会按照重试次数进行重试
	 * @param patientId 病人id
	 * @param doctorId 医生id
	 * @param buyType 购买的类型
	 * @param amount 支付金额
	 * @param orderId 订单号
	 */
	public static void noticeTry(final String patientId, final String doctorId, final String buyType, final BigDecimal amount, final String orderId) {
		DecimalFormat df = new DecimalFormat("##.##");
		final String total = df.format(amount.doubleValue());
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				boolean flag = false;
				for (int i = 0; i < RETRY_TIMES; i++) {
					flag = notice(patientId, doctorId, buyType, total, orderId);
					if (flag) {
						return;
					}
				}
				LOG.error("patientId:"+patientId+",doctorId:"+doctorId+",buyType:"+buyType+",amount:"+amount+",orderId:"+orderId + "---"+RETRY_TIMES+"次重试失败" );
			}
		}).start();
		
	}
	/**
	 * 支付成功后通知app后台,采用post
	 * @param patientId 病人id
	 * @param doctorId 医生id
	 * @param buyType 购买的类型
	 * @param amount 支付金额
	 * @param orderId 订单号
	 * @return 通知成功返回true，失败返回false
	 */
	private static boolean notice(String patientId, String doctorId, String buyType, String amount, String orderId) {
		HttpClient client = HttpClients.createSystem();
		HttpPost post = new HttpPost(NOTICE_URL);
		String result = null;
		try {
			List<NameValuePair> nvps = new ArrayList <NameValuePair>();
			nvps.add(new BasicNameValuePair("PATIENTID", patientId));
			nvps.add(new BasicNameValuePair("DOCTORID", doctorId));
			nvps.add(new BasicNameValuePair("TYPE", buyType));
			nvps.add(new BasicNameValuePair("AMOUNT", amount));
			nvps.add(new BasicNameValuePair("ORDERID", orderId));
			post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
			HttpResponse httpResponse = client.execute(post);
			if(httpResponse.getStatusLine().getStatusCode() == 200) {  
				HttpEntity httpEntity = httpResponse.getEntity();  
				result = EntityUtils.toString(httpEntity);//取出应答字符串 
				if (StringUtils.isBlank(result)) {
					return false;
				}
				
				//JsonMapper jsonMapper = JsonMapper.nonNullMapper();
				JSONObject json = JSONObject.parseObject(StringUtils.trim(result));
				//JSONObject json = jsonMapper.getMapper().();
				if (json.get("RESULT") == null) {
					return false;
				}
				String returnResult = StringUtils.trimToNull(json.getString("RESULT"));
				if (StringUtils.isBlank(returnResult)) {
					return false;
				}
				if ("ERR".equals(returnResult)) {
					LOG.error("patientId:"+patientId+",doctorId:"+doctorId+",buyType:"+buyType+",amount:"+amount+",orderId:"+orderId + "---desc:" + json.getString("DESC"));
					return false;
				} else if ("SUCCESS".equals(returnResult)) {
					return true;
				}
			} 
		} catch (UnsupportedEncodingException e) {
			LOG.error(e.getMessage(), e);
		} catch (ClientProtocolException e) {
			LOG.error(e.getMessage(), e);
		} catch (IOException e) {
			LOG.error(e.getMessage(), e);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return false;  
	}
}
